import React, { useState, useImperativeHandle, RefObject, useEffect } from 'react';

import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import { Modal, Form, Input, message, TreeSelect, Select, Upload } from 'antd';
import type { GetProp, UploadProps } from 'antd';


import { IUser, IRole } from '../../types/user';
import { IDepth } from '../../types/login';

import api from '../../api/index';
import user from '../../api/user';

import NumericInput from '../../components/NumericInput/inxdex';

type FileType = Parameters<GetProp<UploadProps, 'beforeUpload'>>[0];

interface IProps {
    deptRef: RefObject<{
        showModal: (
            type: string,
            data?: IUser,
        ) => void,
    }>;
    upData: () => void;
}

// const getBase64 = (img: FileType, callback: (url: string) => void) => {
//     const reader = new FileReader();
//     reader.addEventListener('load', () => callback(reader.result as string));
//     reader.readAsDataURL(img);
// };

const beforeUpload = (file: FileType) => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
        message.error('You can only upload JPG/PNG file!');
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
        message.error('Image must smaller than 2MB!');
    }
    return isJpgOrPng && isLt2M;
};


const App: React.FC<IProps> = (props) => {

    const [loading, setLoading] = useState(false);
    const [imageUrl, setImageUrl] = useState<string>();

    // 控制弹窗显示隐藏
    const [isModalOpen, setIsModalOpen] = useState(false);
    // action: add 新增 edit 编辑
    const [action, setAction] = useState<string>('add');
    // 部门树数据
    const [treeData, setTreeData] = useState<IDepth[]>([]);
    // 角色列表
    const [roleList, setRoleList] = useState<IRole[]>([]);
    // 表单
    const [form] = Form.useForm();
    // 显示弹窗
    const showModal = (type: string, data?: IUser,) => {
        setAction(type);
        setIsModalOpen(true);
        if (type === 'edit' && data) {
            form.setFieldsValue(data);
            setImageUrl(data.userImg)
        }
    };



    // 保存
    const handleOk = () => {
        // 校验form
        form.validateFields().then(async () => {
            message.success('保存成功');
            handleCancel()
            props.upData();
        })
    };
    // 取消
    const handleCancel = () => {
        form.resetFields();
        setImageUrl('');
        setIsModalOpen(false);
    };


    // 获取部门树数据
    const getTreeData = async () => {
        const data = await api.getDeptList();
        setTreeData(data);
    }
    // 获取角色列表
    const getRoleList = async () => {
        const data = await user.getAllRoleList();
        setRoleList(data);
    }


    useEffect(() => {
        getTreeData()
        getRoleList()
    }, []);

    // 暴露给父组件
    useImperativeHandle(props.deptRef, () => ({
        showModal
    }));

    const handleChange: UploadProps['onChange'] = (info) => {
        if (info.file.status === 'uploading') {
            setLoading(true);
            return;
        }
        if (info.file.status === 'done') {
            setLoading(false);
            const { code, data, msg } = info.file.response;
            if (code === 0) {
                setImageUrl(data.file);
            } else {
                message.error(msg);
            }
        } else if (info.file.status === 'error') {
            message.error('服务器异常，请稍后重试');
        }
    };

    const uploadButton = (
        <button style={{ border: 0, background: 'none' }} type="button">
            {loading ? <LoadingOutlined /> : <PlusOutlined />}
            <div style={{ marginTop: 8 }}>上传头像</div>
        </button>
    );

    return (
        <>
            <Modal
                title={
                    action === 'add' ? '新增用户' : '编辑用户'
                }
                width={800}
                maskClosable={false}
                open={isModalOpen}
                onOk={handleOk}
                onCancel={handleCancel}
                okText="确认"
                cancelText="取消"
            >
                <Form form={form} preserve={false} labelAlign="right" labelCol={{ span: 4 }}>
                    <Form.Item
                        label="角色名称"
                        name="userName"
                        rules={[{ required: true, message: '请输入角色名称' }]}
                    >
                        <Input />
                    </Form.Item>
                    <Form.Item
                        label="角色邮箱"
                        name="userEmail"
                        rules={[
                            { required: true, message: '请输入角色邮箱' },
                            { pattern: /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/, message: '请输入正确的邮箱' },
                            { pattern: /@gmail.com$/, message: '请输入@gmail.com结尾的邮箱' },
                        ]}
                    >
                        <Input />
                    </Form.Item>
                    <Form.Item
                        label="手机号"
                        name="mobile"
                        rules={[
                            { pattern: /^1[3456789]\d{9}$/, message: '请输入正确的手机号' }
                        ]}
                    >
                        <NumericInput placeholder="请输入手机号"></NumericInput>
                    </Form.Item>
                    <Form.Item
                        label="部门"
                        name="deptId"
                        rules={[{ required: true, message: '请选择部门' }]}
                    >
                        <TreeSelect
                            showSearch
                            style={{ width: '100%' }}
                            value={treeData}
                            dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                            fieldNames={{
                                label: 'deptName',
                                value: '_id',
                            }}
                            placeholder="请选择部门"
                            allowClear
                            treeDefaultExpandAll
                            treeData={treeData}
                        />
                    </Form.Item>
                    {/*岗位 */}
                    <Form.Item
                        label="岗位"
                        name="job"
                    >
                        <Input />
                    </Form.Item>
                    {/* 状态 */}
                    <Form.Item
                        label="状态"
                        name="state"
                    >
                        <Select
                            options={[
                                { value: 1, label: '在职' },
                                { value: 2, label: '离职' },
                                { value: 3, label: '试用期' },
                            ]}
                        />
                    </Form.Item>
                    <Form.Item
                        label="角色"
                        name="roleList"
                    >
                        <Select
                            options={roleList.map((item) => ({ value: item._id, label: item.roleName }))}
                        />
                    </Form.Item>
                    <Form.Item
                        label="用户头像"
                        name="userImg"
                    >
                        <Upload
                            listType="picture-circle"
                            showUploadList={false}
                            action="/api/users/upload"
                            beforeUpload={beforeUpload}
                            onChange={handleChange}
                        >
                            {imageUrl ? <img src={imageUrl} alt="avatar" style={{ width: '100%' }} /> : uploadButton}
                        </Upload>
                    </Form.Item>

                </Form>
            </Modal>
        </>
    );
};

export default App;